package com.lfm.friend.service.user.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson2.JSON;
import com.lfm.api.RemoteJudgeService;
import com.lfm.api.domain.UserExeResult;
import com.lfm.core.constants.Constants;
import com.lfm.core.domain.R;
import com.lfm.core.enums.ProgramType;
import com.lfm.core.enums.QuestionResType;
import com.lfm.core.enums.ResultCode;
import com.lfm.core.utils.ThreadLocalUtil;
import com.lfm.api.domain.dto.JudgeSubmitDTO;
import com.lfm.api.domain.vo.UserQuestionResultVO;
import com.lfm.friend.domain.question.Question;
import com.lfm.friend.domain.question.QuestionCase;
import com.lfm.friend.domain.question.es.QuestionES;
import com.lfm.friend.domain.user.UserSubmit;
import com.lfm.friend.domain.user.dto.UserSubmitDTO;
import com.lfm.friend.elasticsearch.QuestionRepository;
import com.lfm.friend.mapper.question.QuestionMapper;
import com.lfm.friend.mapper.user.UserSubmitMapper;
import com.lfm.friend.rabbit.JudgeProducer;
import com.lfm.friend.service.user.IUserQuestionService;
import com.lfm.security.exception.ServiceException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class UserQuestionServiceImpl implements IUserQuestionService {

    @Autowired
    private QuestionRepository questionRepository;
    @Autowired
    private QuestionMapper questionMapper;
    @Autowired
    private UserSubmitMapper userSubmitMapper;
    @Autowired
    private RemoteJudgeService remoteJudgeService;
    @Autowired
    private JudgeProducer judgeProducer;

    @Override
    public R<UserQuestionResultVO> submit(UserSubmitDTO userSubmitDTO) {
        Integer programType = userSubmitDTO.getProgramType();
        if(ProgramType.JAVA.getValue().equals(programType)){
            //按java逻辑处理
            JudgeSubmitDTO junitSubmitDTO = assembleJudgeSubmitDTO(userSubmitDTO);
            return remoteJudgeService.doJudgeJavaCode(junitSubmitDTO);
        }
        throw new ServiceException(ResultCode.FAILED_NOT_SUPPORT_PROGRAM);
    }

    @Override
    public boolean rabbitSubmit(UserSubmitDTO userSubmitDTO) {
        Integer programType = userSubmitDTO.getProgramType();
        if(ProgramType.JAVA.getValue().equals(programType)){
            //按java逻辑处理
            JudgeSubmitDTO junitSubmitDTO = assembleJudgeSubmitDTO(userSubmitDTO);
            judgeProducer.produceMsg(junitSubmitDTO);
            return true;
        }
        throw new ServiceException(ResultCode.FAILED_NOT_SUPPORT_PROGRAM);
    }

    @Override
    public UserQuestionResultVO exeResult(Long examId, Long questionId, String currentTime) {
        Long userId = ThreadLocalUtil.get(Constants.USER_ID, Long.class);
        UserSubmit userSubmit =  userSubmitMapper.selectCurrentUserSubmit(userId, examId, questionId, currentTime);
        UserQuestionResultVO resultVO = new UserQuestionResultVO();
        if(userSubmit == null){
            resultVO.setPass(QuestionResType.IN_JUDGE.getValue());
        }else{
            resultVO.setPass(userSubmit.getPass());
            resultVO.setExeMessage(userSubmit.getExeMessage());
            if(StrUtil.isNotEmpty(userSubmit.getCaseJudgeRes())){
                resultVO.setUserExeResultList(JSON.parseArray(userSubmit.getCaseJudgeRes(), UserExeResult.class));
            }
        }
        return resultVO;
    }

    private JudgeSubmitDTO assembleJudgeSubmitDTO(UserSubmitDTO userSubmitDTO) {
        Long questionId = userSubmitDTO.getQuestionId();
        QuestionES questionES = questionRepository.findById(questionId).orElse(null);
        JudgeSubmitDTO judgeSubmitDTO = new JudgeSubmitDTO();
        if(questionES != null){
            BeanUtil.copyProperties(questionES, judgeSubmitDTO);
        }else{
            Question question = questionMapper.selectById(questionId);
            BeanUtil.copyProperties(question, judgeSubmitDTO);
            questionES = new QuestionES();
            BeanUtil.copyProperties(question, questionES);
            questionRepository.save(questionES);
        }
        judgeSubmitDTO.setUserId(ThreadLocalUtil.get(Constants.USER_ID, Long.class));
        judgeSubmitDTO.setExamId(userSubmitDTO.getExamId());
        judgeSubmitDTO.setProgramType(userSubmitDTO.getProgramType());
        judgeSubmitDTO.setUserCode(codeConnect(userSubmitDTO.getUserCode(), questionES.getMainFuc()));
        String questionCaseJson = questionES.getQuestionCase();
        System.out.println(questionCaseJson);
        List<QuestionCase> questionCaseList = JSONUtil.toList(questionES.getQuestionCase(), QuestionCase.class);
        List<String> inputList = questionCaseList.stream().map(QuestionCase::getInput).collect(Collectors.toList());
        judgeSubmitDTO.setInputList(inputList);
        List<String> outputList = questionCaseList.stream().map(QuestionCase::getOutput).collect(Collectors.toList());
        judgeSubmitDTO.setOutputList(outputList);
        return judgeSubmitDTO;
    }

    private String codeConnect(String userCode, String mainFuc) {
        String targetCharacter = "}";
        int targetLastIndex = userCode.lastIndexOf(targetCharacter);
        if(targetLastIndex != -1){
             return userCode.substring(0, targetLastIndex) + "\n" + mainFuc + "\n" + userCode.substring(targetLastIndex);
        }
        throw new ServiceException(ResultCode.FAILED);
    }
}
